package org.jsola.hr.web;

import kong.unirest.JsonNode;
import org.apache.commons.io.FilenameUtils;
import org.jsola.admin.query.HeaderFieldsQuery;
import org.jsola.admin.vo.HeaderFieldsVO;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.EmpSocInfoAddDTO;
import org.jsola.hr.dto.EmpSocInfoUpdateDTO;
import org.jsola.hr.dto.EmpSocItemListBatchDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.BookingsInfoQuery;
import org.jsola.hr.query.EmpSocInfoQuery;
import org.jsola.hr.query.HeaderFieldsSocQuery;
import org.jsola.hr.service.IEmpSocInfoService;
import org.jsola.hr.vo.*;
import org.jsola.hr.vo.excel.BookingsInfoExportVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;


/**
 * 员工参保信息表
 *
 * @author zhr
 */
@RestController("hrEmpSocInfoController")
@RequestMapping(HrConstants.API_PATH + "/v1/empSocInfos")
public class EmpSocInfoController implements IEmpSocInfoControllerAPI {

    @Autowired
    private IEmpSocInfoService empSocInfoService;


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody EmpSocInfoUpdateDTO empSocInfoUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改员工参保信息表权限校验

        int count = empSocInfoService.update(empSocInfoUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{empSocInfoId}")
    public Result<Integer> delete(@PathVariable String empSocInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除员工参保信息表权限校验

        int count = empSocInfoService.deleteByIds(tokenUser, empSocInfoId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] empSocInfoIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除员工参保信息表权限校验

        int count = empSocInfoService.deleteByIds(tokenUser, empSocInfoIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{empSocInfoId}")
    public Result<EmpSocInfoVO> findById(@PathVariable String empSocInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看员工参保信息表权限校验

        return Result.success(
                empSocInfoService.selectById(empSocInfoId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<EmpSocInfoListVO>> listAll(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看员工参保信息表权限校验

        return Result.success(
                empSocInfoService.select(empSocInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping
    public Result<Page<EmpSocInfoListVO>> page(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.selectPage(empSocInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/getEmpSocInfoMonthList")
    public Result<List<EmpSocInfoListVO>> getEmpSocInfoMonthList(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看员工参保信息表权限校验

        return Result.success(
                empSocInfoService.getEmpSocInfoMonthList(empSocInfoQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/getEmpSocInfoWithEmpInfo")
    public Result<EmpSocInfoVO> getEmpSocInfoWithEmpInfo(@RequestParam("empId") String empId,
                                                         @RequestParam("companyId") String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看员工参保信息表权限校验

        return Result.success(
                empSocInfoService.getEmpSocInfoWithEmpInfo(empId, companyId, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "saveEmpSocInfoNextMonth")
    public Result<String> saveEmpSocInfoNextMonth(@Valid @RequestBody EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工参保信息表权限校验

        return Result.success(
                empSocInfoService.saveEmpSocInfoNextMonth(empSocInfoQuery, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/pageEmpSocInfo")
    public Result<Page<EmpSocInfoListVO>> pageEmpSocInfo(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.selectPageEmpSocInfo(empSocInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/pageEmpSocBack")
    public Result<Page<EmpSocInfoListVO>> pageEmpSocBack(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.selectPageEmpSocBack(empSocInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping(value = "/refunds")
    public Result<EmpSocInfoVO> refunds(@Valid @RequestBody EmpSocInfoAddDTO empSocInfoAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.refunds(empSocInfoAddDTO, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/getAmount")
    public Result<EmpSocInfoListVO> getAmount(String year, String month, String companyId, String monthId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.getAmount(year, month, companyId, monthId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/pageAddEmpSocInfo")
    public Result<Page<EmpSocInfoListVO>> pageAddEmpSocInfo(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.selectPageAddEmpSocInfo(empSocInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping(value = "/setCardinality")
    public Result<Boolean> setCardinality(@Valid @RequestBody EmpSocItemListBatchDTO empSocItemListBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.setCardinality(tokenUser, empSocItemListBatchDTO)
        );
    }

    @Override
    @PostMapping(value = "/setAmount")
    public Result<Boolean> setAmount(@Valid @RequestBody EmpSocItemListBatchDTO empSocItemListBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.setAmount(tokenUser, empSocItemListBatchDTO)
        );
    }

    @Override
    @PostMapping("/bulkEditImport/{monthId}")
    public Result<BulkEditWrongsVO> bulkEditImport(@PathVariable String monthId,
                                                   @RequestParam("file") MultipartFile file) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验
        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                empSocInfoService.bulkEditImport(excelFile, monthId, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportErrorExcel")
    public ResponseEntity<Resource> exportErrorExcel(@RequestBody BulkEditWrongsVO bulkEditWrongsVO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导出权限校验

        String excelFilePath = empSocInfoService.exportErrorListPath(bulkEditWrongsVO, tokenUser);
        // 编码文件名，防止乱码
        String filename = "参保数据错误数据表.xlsx";
        String filenames = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @GetMapping(value = "/selectEmpSocInfoByEmpId")
    public Result<Page<EmpSocInfoListVO>> selectEmpSocInfoByEmpId(@Valid EmpSocInfoQuery empSocInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.selectEmpSocInfoByEmpId(empSocInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/selectYearByEmpId")
    public Result<List<String>> selectYearByEmpId(String empId, String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.selectYearByEmpId(empId, companyId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/selectTimeInfoByProgId")
    public Result<List<EmpSocInfoListVO>> selectTimeInfoByProgId(@Valid String progId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.selectTimeInfoByProgId(progId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/selectEmpIsHaveFillCollectAndNormalDate")
    public Result<List<Date>> selectEmpIsHaveFillCollectAndNormalDate(@RequestParam("empId") String empId,
                                                                      @RequestParam("companyId") String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.selectEmpIsHaveFillCollectAndNormalDate(empId, companyId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/smallProgramGetCurrentUserEmpSocInfo")
    public Result<Page<EmpSocSmallProgramVO>> userEmpSocInfoForMini(@RequestParam("pageSize") Integer pageSize,
                                                                    @RequestParam("pageNo") Integer pageNo) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocInfoService.userEmpSocInfoForMini(pageSize, pageNo, tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/findEmpHaveSocInfo/{empId}")
    public Result<EmpSocInfoVO> findEmpHaveSocInfo(@PathVariable String empId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看社保校验

        return Result.success(
                empSocInfoService.findEmpHaveSocInfo(empId, tokenUser)
        );
    }

    @Override
    @DeleteMapping("/deleteById/{empSocInfoId}")
    public Result<Integer> deleteById(@PathVariable String empSocInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除员工参保信息表权限校验

        int count = empSocInfoService.deleteById(empSocInfoId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping("/getDynamicHead")
    public Result<HeaderFieldsVO> getDynamicHead(HeaderFieldsSocQuery headerFieldsSocQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除员工参保信息表权限校验

        return Result.success(
                empSocInfoService.getDynamicHead(headerFieldsSocQuery, tokenUser)
        );
    }

}

